#include "WCSlider.h"

WCSlider::WCSlider(QWidget *parent)
	: QSlider(parent)
{
	m_value = 0;
	m_mousePress = false;
	m_isMoving = false;

	this->setMouseTracking(true);
}

WCSlider::~WCSlider()
{
}

void WCSlider::mousePressEvent(QMouseEvent *event)
{
	QSlider::mousePressEvent(event);
	setCursor(QCursor(Qt::PointingHandCursor));

	m_isMoving = false;
	m_mousePress = true;
	double pos = event->pos().x() / (double)width();
	double value = pos * (maximum() - minimum()) + minimum();
	if (value > maximum()) {
		value = maximum();
	}
	if (value < minimum()) {
		value = minimum();
	}
	m_value = value + 0.5;
	setValue(m_value);

}

void WCSlider::mouseMoveEvent(QMouseEvent *event)
{
	QSlider::mouseMoveEvent(event);
	setCursor(QCursor(Qt::PointingHandCursor));

	double pos = event->pos().x() / (double)width();
	double value = pos * (maximum() - minimum()) + minimum();
	if (value > maximum()) {
		value = maximum();
	}
	if (value < minimum()) {
		value = minimum();
	}
	if (m_mousePress) {
		m_value = value + 0.5;
		m_isMoving = true;
		setValue(value + 0.5);
	}
	else
	{
		if (m_lastEmitIndex != value + 0.5)
		{
			QPoint point = mapToParent(event->pos());
			emit slideMove(m_lastEmitIndex, value + 0.5, point);
			m_lastEmitIndex = value + 0.5;
		}
	}
}

void WCSlider::mouseReleaseEvent(QMouseEvent *event)
{
	setCursor(QCursor(Qt::CustomCursor));
	m_mousePress = false;
	m_isMoving = false;
	emit sliderReleasedAt(m_value);
	QSlider::mouseReleaseEvent(event);
}

void WCSlider::leaveEvent(QEvent *event)
{
	emit slideRelease();
	m_lastEmitIndex = -1;
	QSlider::leaveEvent(event);
}
